package com.smu.controller;

import com.smu.entity.Girl;
import com.smu.entity.Result;
import com.smu.repository.GirlResitory;
import com.smu.service.GirlService;
import org.aspectj.apache.bcel.util.ClassLoaderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by smwsk
 * 2017/4/3.
 */
@RestController
@Transactional
public class GirlController {
    @Autowired
    private GirlResitory girlResitory;
    @Autowired
    private GirlService girlService;

    @RequestMapping(value = "/findAll")
    public List<Girl> findAll(){
        return girlResitory.findAll();
    }
    @PostMapping(value = "/save")
    public Map<String,Object> save(@Valid Girl girl, BindingResult bindingResult)
    {
        Map<String,Object> map= new HashMap<String,Object>();
        if (bindingResult.hasErrors()){
            map.put("faile",bindingResult.getFieldError().getDefaultMessage());
            return map;
        }else{
            map.put("Success",girlResitory.save(girl));
            return map;
        }
    }
    @RequestMapping(value = "/saveAndFlush")
    public Girl saveAndFlush(Girl girl){
        return  girlResitory.saveAndFlush(girl);
    }
    @RequestMapping(value = "/delete")
    public String delete(int id){
        try {
            girlResitory.delete(id);
            return "success";
        }catch (Exception e){
            return "faile";
        }
    }
    @GetMapping(value = "/getgirl/{id}")
    public Girl getgril(@PathVariable("id") Integer id){
        return girlResitory.findOne(id);
    }

    @GetMapping(value = "/getAge/{id}")
    public Result getAge(@PathVariable("id") Integer id) throws Exception {
        Result result = girlService.getAge(id);
        return result;
    }
}
